package com.zh.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zh.constants.Constants;
import com.zh.pojo.bo.PayResultBo;
import com.zh.pojo.domain.PayOrder;
import com.zh.pojo.domain.WxpayFlow;
import com.zh.service.IPayOrderService;
import com.zh.utils.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.util.HashMap;

// MQ事务监听器

@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup = Constants.MQ.TX_GROUP_PAY_ORDER_RESULT)
public class PayResultListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService orderService;

    /**
     * @param message 构建消息
     * @param args 扩展参数
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object args) {
        try {
            // 扩展参数就是自己 执行本地事务操作的 对象
            HashMap<String, Object> orderData = (HashMap<String, Object>) args;
            PayOrder payOrder = (PayOrder) orderData.get("payOrder");
            WxpayFlow wxpayFlow = (WxpayFlow) orderData.get("wxpayFlow");
            //  修改支付单状态 ， 保存订单流水
            orderService.updatePayOrderAndSaveFlow(payOrder,wxpayFlow);
            // 本地事务保存成功则 发送提交命令
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e) {
            e.printStackTrace();
            // 发送消息失败则 提交回滚命令
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    /**
     * 回查机制，  根据订单号 查询数据库中订单状态是否修改成功，
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        PayResultBo payResultBo = (PayResultBo) message.getPayload();
        PayOrder payOrder = orderService.getOne(new LambdaQueryWrapper<PayOrder>().eq(PayOrder::getOrderNo, payResultBo.getOrderNo()));
        AssertUtil.isNotNull(payOrder, "订单不存在");
        // 订单状态是否修改成功
        if (payOrder.getPayStatus().equals(Constants.pay.PAY_STATUS_SUCCESS)) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
